/**
 * 将元素设置为可移动的
 * @param removableElem 可移动的元素，该元素必须被设置为position，才能够被移动
 * @param parentElem 移动元素的父容器，用于限定移动元素的移动范围；若不指定则相对于document
 * @param options 控制参数,格式 {
        //元素移动结束时的回调函数，将返回相对于给定父元素的位置
        overCall: function (x ,y) {
            console.log(x + " : " + y);
        }
        //是否移动x坐标
        ,isMoveX: true
        //是否移动y坐标
        ,isMoveY: true
    }
 */
system.setToRemovable = function(removableElem,parentElem ,options){
    var inOptions = {
        //移动元素时回调
        moveCall: function (x,y) {}
        //元素移动结束时的回调函数，将返回相对于给定父元素的位置
        ,overCall: function (x ,y) {}
        //是否移动x坐标
        ,isMoveX: true
        //是否移动y坐标
        ,isMoveY: true
    }
    $.extend(inOptions ,options);
    //结果，移动的距离
    var moveX ,moveY;
    //鼠标点击时，元素所处位置
    var x ,y;
    //是否点下，即选中移动元素
    var downFlag;
    //可移动距离
    var minScopeX ,minScopeY,maxScopeX,maxScopeY;
    //设置可移动范围
    if(parentElem){
        minScopeX = $(parentElem).width() < $(removableElem).width() ?  $(parentElem).width() - $(removableElem).width() : 0;
        minScopeY = $(parentElem).height() < $(removableElem).height() ?  $(parentElem).height() - $(removableElem).height() : 0;
        maxScopeX = minScopeX < 0 ? $(removableElem).width() - $(parentElem).width() + $(removableElem).position().left  : $(parentElem).width() - $(removableElem).width();
        maxScopeY = minScopeY < 0 ? $(removableElem).height()-$(parentElem).height() + $(removableElem).position().top  : $(parentElem).height()- $(removableElem).height();
    }else{
        parentElem = document;
    }
    //绑定可移动元素的鼠标点下事件
    $(removableElem).mousedown(function (e) {
        x = e.pageX - parseInt($(removableElem).position().left);
        y = e.pageY - parseInt($(removableElem).position().top);
        downFlag = true;
    })
    
    //绑定父容器的鼠标移动事件
    $(parentElem).mousemove(function (e) {
        if (downFlag) {
            var movedX = false;
            var movedY = false;
            var inMoveX = e.pageX - x;var inMoveY = e.pageY - y;
            if((minScopeX == undefined || inMoveX >= minScopeX) && (maxScopeX == undefined || inMoveX <= maxScopeX)) {
                if(inOptions.isMoveX){
                    $(removableElem).css("left", inMoveX);
                }
                movedX = true;
                moveX = inMoveX;
            }
            if((minScopeY == undefined || inMoveY >= minScopeY) && (maxScopeY == undefined || inMoveY <= maxScopeY)){
                if(inOptions.isMoveY){
                    $(removableElem).css("top", inMoveY);
                }
                movedY = true;
                moveY = inMoveY;
            }
            //超出范围
            if(!movedX || !movedY){
                downFlag = false;
                if (inOptions.overCall) {
                    inOptions.overCall(moveX, moveY);
                }
            }
            //回调
            if(inOptions.moveCall){
                inOptions.moveCall(movedX ? moveX : undefined ,movedY ? movedY : undefined);
            }
        }
        return false;
    })

    //绑定父容器鼠标释放事件：不在移动元素
    $(parentElem).mouseup(function (e) {
        if(downFlag) {
            downFlag = false;
            if (inOptions.overCall) {
                inOptions.overCall(moveX, moveY);
            }
        }
    })
}

system.lz = function(i,c)
{
    if( typeof c != 'number' || c <= 0 || (typeof i != 'number' && typeof i != 'string') )
    { return i; }
    i+='';

    while( i.length < c )
    { i='0'+i; }
    return i;
}

system.getHashCode = function(s)
{
    var hash=0,c=(typeof s == 'string')?s.length:0,i=0;
    while(i<c)
    {
        hash = ((hash<<5)-hash)+s.charCodeAt(i++);
        //hash = hash & hash; // Convert to 32bit integer
    }

    return ( hash < 0 )?((hash*-1)+0xFFFFFFFF):hash; // convert to unsigned
};

system.uniqueId = function( s, bres )
{
    if( s == undefined || typeof s != 'string' )
    {
        if( !system.___uqidc )
        { system.___uqidc=0; }
        else { ++system.___uqidc; }
        var od = new Date(),
            i = s = od.getTime()+''+system.___uqidc;
    }
    else { var i = system.getHashCode( s ); }
    return ((bres)?'res:':'')+i.toString(32)+'-'+system.lz((s.length*4).toString(16),3);
};

/**
 * 打开等待提示界面
 * @param msg 提示消息
 * @param ele 添加容器，可为空，默认为body
 */
system.openWaitAlter = function(msg ,elem){
    var $waitAlter = $('<div class="waiting-alter" style="opacity:0.5;width:100%;height:100%;float: left;position:fixed;left:0px;top:0px;text-align: center;z-index: 9999;background-color: black;padding-top: 10%;color: white" >\n' +
        '    <i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 30px; color: #1E9FFF;"></i>\n' +
        '    <p>'+msg+'...</p>\n' +
        '</div>');
    elem ? $(elem).append($waitAlter) : $('body').append($waitAlter);
}
/**
 * 关闭等待提示界面
 * @param elem 存入容器，可为空，默认从body中获取
 */
system.closeWaitAlter = function(elem){
    var $e = elem ? $(elem) : $('body');
    $e.find('[class=waiting-alter]').remove();
}


/**
 * 打开数据选择器页面，可在该页面选择数据，并应用到当前页面；
 * 使用提示：需要在选择页面中应用到数据调用system.useSelectorData 方法
 * @param dataUri 数据选择器页面请求地址
 * @param callDataContainerId 选择数据回调复制容器id ，可为空，默认为：formContainer
 * @param selectorTitle 数据选择器页面显示标题 ,默认为： 数据选择
 */
system.openDataSelector = function(dataUri ,callDataContainerId ,selectorTitle ,callFn){
    if(!dataUri){
        system.error("数据请求uri不能为空");
    }
    var wrapperContainerId = callDataContainerId ? (callDataContainerId.indexOf("#") == 0 ? callDataContainerId : "#" + callDataContainerId) : "#formContainer";
    var wrapperTitle = selectorTitle ? selectorTitle : "数据选择";
    var wrapperDataUri = dataUri.indexOf(system.contextPath) == 0 ? dataUri : system.contextPath + dataUri;
    var selectorKey = "DATA_SELECTOR#" + selectorTitle +"#"+ dataUri + "#" + callDataContainerId;
    var selectorPageId = layui.layer.open({
        selectorKey: selectorKey,
        type: 2,
        title: wrapperTitle,
        area: ['100%', '90%'],
        content: wrapperDataUri ,
        success: function (layero, index) {
            var body = layer.getChildFrame('body', index);
            $(body).append($('<input type="hidden" value="'+ selectorKey +'" id="DATA_SELECTOR_SELECTOR_KEY">'));
        },
        end: function () {
            //获取容器中到值
            var selectorInfo = top.window[selectorKey];
            if(callFn){
                callFn(selectorInfo);
            }else{
                $(selectorInfo.containerId).find("[name]").each(function () {
                    var $this = $(this);
                    var name = $this.attr("name");
                    var value = selectorInfo.data[name];
                    if (value) {
                        $this.val(value).text(value);
                    }
                });
            }
            //清空缓存
            top.window[selectorInfo] = null;
        }
    });
    top.window[selectorKey] = {pageId: selectorPageId ,containerId: wrapperContainerId ,data : {}};
}

/**
 * 图片宽高验证
 * @param options {base64: "图片base64 ，与file字段而选一"
 * ，file: "上传图片的input，与base64二选一 " ,width: "要求宽度" ,height: "要求高度" ,success: "通过回调" ,error: "未通过回调"}
 */
system.imgWHCheck = function (options) {
    function base64(options){
        // 创建对象
        var img = new Image();
        img.src = options.base64;
        img.onload = function () {
            if(options.width && options.width > 0 && options.height && options.height > 0 ){
                if(img.width == options.width && img.height == options.height){
                    options.success ? options.success() : '';
                    return;
                }
            }else if(options.width && options.width > 0){
                if(img.width == options.width){
                    options.success ? options.success() : '';
                    return;
                }
            }else if(options.height && !options.height > 0 ){
                if(img.height == options.height){
                    options.success ? options.success() : '';
                    return;
                }
            }else{
                //不校验图片尺寸
                options.success ? options.success() : '';
                return;
            }
            options.error ? options.error() : console.log('图片尺寸不合法，宽度: ' + img.width + " ,高度：" + img.height);
        }
    }
    if(options.base64){
        base64(options);
    }else if(options.file){
        var filePic = options.file.files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            var data = e.target.result;
            console.log(data)
            options['base64'] = data;
            base64(options);
        };
        reader.readAsDataURL(filePic);
    }else{
        options.error ? options.error() : console.log("无验证图片");
    }
}

/**
 * 应用选择器数据
 */
system.useSelectorData = function(dataJson){
    if(!dataJson){
        system.error("应用数据不能为空");
    }
    var selectorInfo = top.window[$('#DATA_SELECTOR_SELECTOR_KEY').val()];
    if (!selectorInfo) {
        system.error("应用失败，回调容器不存在");
    } else {
        //赋值给selectorKey中，等待回调赋值
        selectorInfo.data = dataJson;
        //关闭选择层
        parent.layer.close(selectorInfo.pageId);
    }
}

/**
 * 应用数据模板
 * @param dataContainerId 当前数据容器id
 */
system.useTemplate = function (dataContainerId) {
    system.openDataSelector('/common/dataTemplate/list' ,dataContainerId ,'模板应用');
}

/**
 * 添加数据模板
 * @param dataContainerId 当前数据容器id
 */
system.buildTemplate = function (dataContainerId) {
    var containerId = dataContainerId ? (dataContainerId.indexOf("#") == 0 ? dataContainerId : "#" + dataContainerId) : "#formContainer";
    var templateData = {};
    $(containerId).find("[name]").each(function () {
        var $this = $(this);
        var value = $this.val() ? $this.val() : $this.text();
        templateData[$this.attr("name")] = value;
    });
    var templateDataJson = JSON.stringify(templateData);
    top.window['templateDataJson'] = templateDataJson;

    layui.layer.open({
        type: 2,
        title: '设置为模板',
        area: ['100%', '80%'],
        content: system.contextPath + '/common/dataTemplate/toBuildTemplate'
    });
}

system.uploadPath = function () {
    return system.contextPath + '/resource/core/upload';
}
system.info = function (info) {
    top.layer.msg(info, {icon: 6});
};
system.success = function (info) {
    top.layer.msg(info, {icon: 1});
};
system.error = function (info) {
    top.layer.msg(info, {icon: 2});
};
system.confirm = function (tip, ensure) {
    top.layer.confirm(tip, {
        skin: 'layui-layer-admin'
    }, function () {
        ensure();
    });
};
system.copy = function copyContent(content) {
    var $input = $('<input readonly="readonly" value=\'' + content + '\'/>');
    $("body").append($input);
    $input[0].select();
    document.execCommand('copy') ? system.success("复制成功") : system.error("复制失败");
    $input.remove();
}
system.currentDate = function () {
    // 获取当前日期
    var date = new Date();

    // 获取当前月份
    var nowMonth = date.getMonth() + 1;

    // 获取当前是几号
    var strDate = date.getDate();

    // 添加分隔符“-”
    var seperator = "-";

    // 对月份进行处理，1-9月在前面添加一个“0”
    if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
    }

    // 对月份进行处理，1-9号在前面添加一个“0”
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }

    // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
    return date.getFullYear() + seperator + nowMonth + seperator + strDate;
};
system.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
};
system.infoDetail = function (title, info) {
    var display = "";
    if (typeof info === "string") {
        display = info;
    } else {
        if (info instanceof Array) {
            for (var x in info) {
                display = display + info[x] + "<br/>";
            }
        } else {
            display = info;
        }
    }
    top.layer.open({
        title: title,
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['950px', '600px'], //宽高
        content: '<div style="padding: 20px;">' + display + '</div>'
    });
};
system.zTreeCheckedNodes = function (zTreeId) {
    var zTree = $.fn.zTree.getZTreeObj(zTreeId);
    var nodes = zTree.getCheckedNodes();
    var ids = "";
    for (var i = 0, l = nodes.length; i < l; i++) {
        ids += "," + nodes[i].id;
    }
    return ids.substring(1);
};

// 以下代码是配置layui扩展模块的目录，每个页面都需要引入
layui.config({
    base: system.contextPath + '/plugins/module/'
}).extend({
    formSelects: 'formSelects/formSelects-v4',
    treetable: 'treetable-lay/treetable',
    dropdown: 'dropdown/dropdown',
    notice: 'notice/notice',
    step: 'step-lay/step',
    dtree: 'dtree/dtree',
    citypicker: 'city-picker/city-picker',
    tableSelect: 'tableSelect/tableSelect',
    ax: 'ax/ax',
    ztree: 'ztree/ztree-object'
}).use(['admin'], function () {
    var $ = layui.$;
    var admin = layui.admin;

    // 单标签模式需要根据子页面的地址联动侧边栏的选中，用于适配浏览器前进后退按钮
    if (window != top && top.layui && top.layui.index && !top.layui.index.pageTabs) {
        top.layui.admin.activeNav(location.href.substring(system.contextPath.length));
    }

    // 移除loading动画
    setTimeout(function () {
        admin.removeLoading();
    }, window == top ? 300 : 150);

    //注册session超时的操作
    $.ajaxSetup({
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        complete: function (XMLHttpRequest, textStatus) {

            //通过XMLHttpRequest取得响应头，sessionstatus，
            var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
            if (sessionstatus === "timeout") {

                //如果超时就处理 ，指定要跳转的页面
                window.location = system.contextPath + "/global/sessionError";
            }
        }
    });

});